#include <wx/wx.h>
#include <wx/filename.h>
#include <wx/stdpaths.h>
#include "cfgmgr.h"
#include "common.h"

ConfigManager::ConfigManager(wxInputStream& is) :
    wxFileConfig(is) {
    wxLogMessage(_T("ConfigManager::ConfigManager"));
    
    /*if(wxTheApp!=NULL) {
     wxTheApp->SetAppName(app_name); // !important!
     }*/
    
    this->_init_paths();
}

void ConfigManager::set_appname(const wxString& app_name) {
    appname = app_name;
    
    app_cfgfile_path = wxFileName(wxStandardPaths::Get().GetUserDataDir(), appname+ _T(".cfg")); // ~/.daodict/daodict.cfg
    app_cfgfile_path.Mkdir(0777, wxPATH_MKDIR_FULL);
    
    if ( !app_cfgfile_path.FileExists() ) {
        wxFFile file(app_cfgfile_path.GetFullPath(), _T("w+b")); // create a empty config file;
    }
}

void ConfigManager::_init_paths() {
    wxStandardPaths& std_paths = (wxStandardPaths&)wxStandardPaths::Get();
    
#ifdef __WXGTK__ // set unix install prefix
    wxFileName exedir_fn(std_paths.GetExecutablePath());
    exedir_fn.RemoveLastDir();
    std_paths.SetInstallPrefix(exedir_fn.GetPath());
#endif
    
    // init Global Resources Directory
    global_res_dir = wxFileName(std_paths.GetResourcesDir(), wxEmptyString);
    
    // init Global Data Directory
    global_data_dir = wxFileName(std_paths.GetDataDir(), wxEmptyString);
    
    // init User Data Directory
    user_data_dir = wxFileName(std_paths.GetUserDataDir(), wxEmptyString);
    user_data_dir.Mkdir(0777, wxPATH_MKDIR_FULL);
    
    // init log file path
    app_logfile_path = wxFileName(user_data_dir);
    wxDateTime now = wxDateTime::Now();
    app_logfile_path.SetFullName(wxString::Format(_T("%s.%d-%d-%d.%d.log"), appname.c_str(),
    now.GetYear(), now.GetMonth()+1, now.GetDay(), dao_get_timezone()));
    
    // init product theme dir
    product_theme_dir = wxFileName(global_data_dir);
    product_theme_dir.AppendDir(_T("theme"));
    
    // init product dictpack dir
    product_dictpack_dir = wxFileName(global_data_dir);
    product_theme_dir.AppendDir(_T("dictpack"));
    
    // init product product_mgrdb_path
    product_mgrdb_path = wxFileName(user_data_dir);
    product_mgrdb_path.SetFullName(_T("mgrdb.data"));
}

ConfigManager* ConfigManager::_cfg_mgr= NULL;
wxFileName ConfigManager::app_cfgfile_path;
wxString ConfigManager::appname;
